package edu.vt.ece4564.bluetendance.classes;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import edu.vt.ece4564.bluetendance.database.DatabaseConnector;

public class ClassListingGetter implements Runnable {
	
	private String userName;
	private HttpServletResponse response;

	public ClassListingGetter(HttpServletResponse response, String userName) {
		this.response = response;
		this.userName = userName;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void run() {
		DatabaseConnector dc = DatabaseConnector.get();
		
		dc.commandText = "call SP_GetClassesForUser('" + userName + "');";
		ResultSet classListingResults = dc.executeQuery();
		
		List<Class> listOfClasses = new ArrayList<Class>();

		try {
			while (classListingResults.next()) {
				listOfClasses.add(new Class(classListingResults.getInt("ClassID"), classListingResults.getString("ClassName")));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		response.setContentType("application/plain");

		PrintWriter out = null;
		
		try {
			out = response.getWriter();
		}
		catch (IOException e) {
			e.printStackTrace();
		}

		if (listOfClasses.size() > 0) {
			JSONArray array = new JSONArray();
			JSONObject obj = new JSONObject();
			obj.put("NumberOfClasses", listOfClasses.size());
			int classNum = 0;
			for (Class newClass : listOfClasses) {
				obj.put("ClassID" + classNum, newClass.getClassID());
				obj.put("ClassName" + classNum, newClass.getClassName());
				classNum++;
			}
			array.add(obj);
			
			StringBuilder sb = new StringBuilder(array.toString());
			if (sb.charAt(0) == '[') {
				sb.deleteCharAt(0);
			}
			if (sb.charAt(sb.length() - 1) == ']') {
				sb.deleteCharAt(sb.length() - 1);
			}
			out.println(sb);
		}
		else {
			JSONObject obj=new JSONObject();

			obj.put("valid","false");
			out.println(obj.toString());
		}
		out.close();
	}
}
